require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

local type = type;

UICharactorInfoArchives = {};
HelperFunc.SetUIEnv(UICharactorInfoArchives)
local this = UICharactorInfoArchives;

-- this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.currentHeroData = nil;
this.roleInfoConfig = nil;

this.hasInit = false;

this.objModel = nil;
this.txtBaseArchivesTitle = nil;
this.txtResumeTitle = nil;
this.txtHeroTitle = nil;
this.txtHeroName = nil;
this.heroType = nil;
---@type FairyGUI.GList
this.rectContent = nil;
this.txtArcNameTitle = nil;
this.txtArcName = nil;
this.txtArcSexTitle = nil;
this.txtArcSex = nil;
this.txtArcRaceTitle = nil;
this.txtArcRace = nil;
this.txtArcAgeTitle = nil;
this.txtArcAge = nil;
this.txtArcBornTitle = nil;
this.txtArcBorn = nil;
this.txtArcHeightTitle = nil;
this.txtArcHeight = nil;
this.txtIntro = nil;
this.btnBackBtn = nil;
this.archivesTable = {};
this.objModel = nil
this.drawWrapper = nil
this.graphic = nil
this.audioList = {}
this.comments_data_list = {}
function UICharactorInfoArchives.Init(heroData, index)
    --todo 应该小写 暂时先大写
    this.currentHeroData = heroData;

    this.cur_select_tab_index = index or 0
    if this.roleInfoConfig == nil then
        this.roleInfoConfig = G.dataTable["t_roleinfo"];
    end
    this.cur_hero_is_unown = logicMgr.HeroManager.NotHaveByModeId(this.currentHeroData.partnerModelId)  
    local name, package = getUIName(PanelNames.UICharactorInfoArchives);
    panelMgr:ShowUI(name, package, this.onCreate, Config.useLocalUI);
end
---@param obj FairyGUI.GComponent
function UICharactorInfoArchives.onCreate(obj)
    -- this.gameObject = obj;
    --transform = obj.transform;
    -- = transform:GetComponent('LuaBehaviour');
    if not this.hasInit then
        this.hasInit = true
        this.txtHeroTitle = obj:GetChild("HeroTitleText")
        this.txtHeroName = obj:GetChild("HeroNameText")
        this.heroType = obj:GetChild("HeroType")
        this.rectContent = obj:GetChild("ScrollView")
        this.rectContent:RemoveChildrenToPool()
        this.rectContent:AddItemFromPool()
        local achieve = this.rectContent:GetChildAt(0)
        this.txtBaseArchivesTitle = achieve:GetChild("BaseArchivesText")
        this.txtResumeTitle = achieve:GetChild("ResumeText")
        this.txtArcNameTitle = achieve:GetChild("ArcNameTitle")
        this.txtArcName = achieve:GetChild("ArcNameText")
        this.txtArcSexTitle = achieve:GetChild("ArcSexTitle")
        this.txtArcSex = achieve:GetChild("ArcSexText")
        this.txtArcRaceTitle = achieve:GetChild("ArcRaceTitle")
        this.txtArcRace = achieve:GetChild("ArcRaceText")
        this.txtArcAgeTitle = achieve:GetChild("ArcAgeTitle")
        this.txtArcAge = achieve:GetChild("ArcAgeText")
        this.txtArcBornTitle = achieve:GetChild("ArcBornTitle")
        this.txtArcBorn = achieve:GetChild("ArcBornText")
        this.txtArcHeightTitle = achieve:GetChild("ArcHeightTitle")
        this.txtArcHeight = achieve:GetChild("ArcHeightText")
        this.txtIntro = achieve:GetChild("IntroText")
        this.btnBackBtn = obj:GetChild("BackBtn")
        this.btnbgClose = obj:GetChild("bgClose")
        this.graphic = obj:GetChild("CharactormaskNew"):GetChild("Charactormask")

        this.btnInfo = obj:GetChild("btnInfo")
        this.btnVoice = obj:GetChild("btnVoice")
        this.btnPageLeft = obj:GetChild("btnPageLeft")
        this.btnPageright = obj:GetChild("btnPageright")
        this.Txt_CvName = obj:GetChild("Txt_CvName")
        this.Txt_IntroVoice = obj:GetChild("Txt_IntroVoice")
        this.List_Voice = obj:GetChild("Comp_VoiceList"):GetChild("List_Voice")
        this.List_Voice.itemRenderer = this.renderListItemVoice
        this.ShowLineTextController = obj:GetController("showLineText")

        this.btnPageright.grayed =this.List_Voice.scrollPane.percX == 1
        this.btnPageLeft.grayed = this.List_Voice.scrollPane.percX == 0

        --方向提示灰化
        this.List_Voice.scrollPane.onScroll:Add(function()
            this.btnPageright.grayed =this.List_Voice.scrollPane.percX == 1
            this.btnPageLeft.grayed = this.List_Voice.scrollPane.percX == 0
        end)

        this.tab_controller = obj:GetController("func")
        this.tab_controller:SetSelectedIndex(this.cur_select_tab_index)
  
        -- 英雄评论相关
        this.comment_btn = obj:GetChild("btnComment")
        if Config.OpenCommentAndBullet then 
            this.comment_btn.visible = true
            this.comment_btn.touchable = true
        else
            this.comment_btn.visible = false
            this.comment_btn.touchable = false
        end
        this.list = obj:GetChild("list")
        this.list:RemoveChildrenToPool()
        this.list.itemRenderer = this.renderListItemComment 
        this.list:SetVirtual()
        this.comment_num = obj:GetChild("text")
        this.like_num = obj:GetChild("numLike")
        this.like_btn = obj:GetChild("btnLike")
        local like_btn_title = this.like_btn:GetChild("title")
        like_btn_title.text = getLanguage("Achieve_HeroComment_Like")
        this.like_sp = this.like_btn:GetChild("n6") 
        this.like_hero_count = 0 
        this.like_num.text = this.like_hero_count
        this.comment_num.text = getLanguage("Achieve_HeroComment_Count").."：0"

        local comment_obj = obj:GetChild("input")
        this.commend_send_btn = comment_obj:GetChild("btnConfirm")
        this.commend_input_content = comment_obj:GetChild("InputText")
        this.commend_input_content.text = ""
        this.commend_input_content.promptText = getLanguage("Achieve_HeroComment_InputHint")
        this.comment_input_controller = comment_obj:GetController("state") 
        this.comment_input_tips1 = comment_obj:GetChild("tips1")
        this.comment_input_tips2 = comment_obj:GetChild("tips2") 
        -- end

        this.addEvent();
    end
    this.selectedVoiceIndex = 1

    -- if Config.OpenCommentAndBullet then 
    --     logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UICharactorInfoArchives,Config.FuncOpenType.HeroComment, this.comment_btn.name, this.comment_btn);
    -- end
    
    this.txtBaseArchivesTitle.text = getLanguage("Sys_Archives");
    this.txtResumeTitle.text = getLanguage("Sys_Resume");
    this.txtArcNameTitle.text = getLanguage("Sys_RoleName");
    this.txtArcSexTitle.text = getLanguage("Sys_RoleSex");
    this.txtArcRaceTitle.text = getLanguage("Sys_RoleRace");
    this.txtArcAgeTitle.text = getLanguage("Sys_RoleAge");
    this.txtArcBornTitle.text = getLanguage("Sys_RoleBirthday");
    this.txtArcHeightTitle.text = getLanguage("Sys_RoleHeight");

    local useSkinId = logicMgr.SkinManager.getHeroSkinId(this.currentHeroData.partnerModelId)
    local path = logicMgr.SkinManager.GetHeroDrawPathBySkinId(useSkinId)
    resMgr:LoadModelPrefab( path, function(go)
        if this.objModel ~= nil then
            destroy(this.objModel);
        end
        if not this.drawWrapper then
            this.drawWrapper = GoWrapper.New();
        end
        local model = newObject(go);
        model:SetActive(true);
        this.objModel = model
        model:AddComponent(TCanvas);
        this.drawWrapper:SetWrapTarget(model, false)
        this.graphic:SetNativeObject(this.drawWrapper)
        local tempPos = Vector3.New(this.currentHeroData.location[1], this.currentHeroData.location[2], 0)
        Util.Lua_SetLocalPositionXYZ(model.transform, tempPos.x, tempPos.y, tempPos.z)
        local tempScale = Vector3.New(this.currentHeroData.scale[1], this.currentHeroData.scale[2], 1);
        Util.Lua_SetLocalScaleXYZ(model.transform, tempScale.x, tempScale.y, tempScale.z)
        Util.AddAction(this.objModel, "idle1", true)
        this.objModel:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 3);
        this.objModel:GetComponent("SkeletonGraphic").material:SetFloat("_Stencil",1);
    end);

    this.refresh();
    if this.cur_select_tab_index == 0 then
        this.onClickInfoPanel()
    elseif this.cur_select_tab_index == 1 then
        this.onClickVoicePanel()
    elseif this.cur_select_tab_index == 2 then
        this.onClickCommentPanel()
    end
end

function UICharactorInfoArchives.addEvent()
    this.btnBackBtn.onClick:Add(this.onClickBack)
    this.btnbgClose.onClick:Add(this.onClickBack)
    this.btnInfo.onClick:Add(this.onClickInfoPanel)
    this.btnVoice.onClick:Add(this.onClickVoicePanel)
    this.btnPageLeft.onClick:Add(this.onClickLeftPage)
    this.btnPageright.onClick:Add(this.onClickRightPage)
    this.List_Voice.onClickItem:Add(this.onClickItemVoice)
    --LuaBehaviour:AddClick(btnBackBtn.gameObject, this.onClickBack);

    this.comment_btn.onClick:Add(this.onClickCommentPanel)
    this.like_btn.onClick:Add(this.onClickLikeHero) 
    this.commend_send_btn.onClick:Add(this.onClickSendComment) 
    -- this.commend_input_content.onFocusOut:Add(this.OnFocusOutInput)
    this.commend_input_content.onChanged:Add(this.OnInputChange)
end

function UICharactorInfoArchives.removeEvent()
    this.btnbgClose.onClick:Remove(this.onClickBack)
    this.btnBackBtn.onClick:Remove(this.onClickBack)
    this.btnInfo.onClick:Remove(this.onClickInfoPanel)
    this.btnVoice.onClick:Remove(this.onClickVoicePanel)
    this.btnPageLeft.onClick:Remove(this.onClickLeftPage)
    this.btnPageright.onClick:Remove(this.onClickRightPage)
    this.List_Voice.onClickItem:Remove(this.onClickItemVoice)
    this.List_Voice.scrollPane.onScroll:Clear()
    --LuaBehaviour:RemoveClick(btnBackBtn.gameObject);

    this.comment_btn.onClick:Remove(this.onClickCommentPanel)
    this.like_btn.onClick:Remove(this.onClickLikeHero)
    this.commend_send_btn.onClick:Remove(this.onClickSendComment) 
    -- this.commend_input_content.onFocusOut:Remove(this.OnFocusOutInput)
    this.commend_input_content.onChanged:Remove(this.OnInputChange)
end

-- 输入框输入变化 
function UICharactorInfoArchives.OnInputChange() 
    local content = this.commend_input_content.text
    content = string.gsub(content,"\r", "")
    content = string.gsub(content,"\n", "") 
    if this.limit_send_content_count == nil then
        this.limit_send_content_count = dataTable.getDataTableByStringId("t_global",281,"f_int_value") or 30
    end  
    content = string.limitstr(content, this.limit_send_content_count)
    this.commend_input_content.text = content 
end

-- function UICharactorInfoArchives.OnFocusOutInput()
    -- print("OnFocusOutInput")
    -- if IsWindowEditor() then
    --     return
    -- end
    -- if string.IsNilOrEmpty(this.commend_input_content.text) then return end
    -- this.onClickSendComment()
-- end

function UICharactorInfoArchives.LocalListenEvent()
  
end

function UICharactorInfoArchives.LocalCloseEvent()

end

function UICharactorInfoArchives.OnDestroy()
    this.removeEvent()
    this.comment_btn = nil
    this.list = nil
    this.comment_num = nil
    this.like_num = nil
    this.like_btn = nil
    this.like_sp = nil  
    this.commend_send_btn = nil
    this.commend_input_content = nil
    this.comment_input_controller = nil
    this.comment_input_tips1 = nil
    this.comment_input_tips2 = nil
    if this.objModel ~= nil then
        destroy(this.objModel);
    end
end

function UICharactorInfoArchives.OnEnable()
    this.LocalListenEvent()
end

function UICharactorInfoArchives.OnDisable()
    this.checkStopVoice()
    this.LocalCloseEvent();
    if this.objModel ~= nil then
        destroy(this.objModel);
    end
end

function UICharactorInfoArchives.refresh()
    if not logicMgr.HeroManager.NotHaveByModeId(this.currentHeroData.partnerModelId) then
        this.currentHeroData=logicMgr.HeroManager.getHeroDatabyPartnerId((this.currentHeroData or {}).partnerId or 0,true)or {}
    end
    if table.isNullOrEmpty(this.currentHeroData) or table.isNullOrEmpty(this.roleInfoConfig)then
        logError("配置未找到,或英雄信息为空");
        return ;
    end
    this.currentHeroData.favorLv=this.currentHeroData.favorLv or 0
    local curRoleInfoConfig = this.roleInfoConfig[tostring(this.currentHeroData.partnerModelId)];
    if curRoleInfoConfig == nil then
        logError(string.format("未找到id为%d的配置，T_RoleInfo", this.currentHeroData.partnerModelId));
        return ;
    end
    this.heroType.url = "ui://ICONAtlas/" .. EnumConst.HeroTypeIcon[this.currentHeroData.type]
    this.txtHeroName.text = this.currentHeroData.name;
    this.txtHeroTitle.text = this.currentHeroData.subName;
    this.txtArcName.text = this.currentHeroData.name;
    this.txtArcSex.text = getLanguage(string.format(Config.LangRoleSex, curRoleInfoConfig["f_RoleSex"]));
    this.txtArcRace.text = getLanguage(string.format(Config.LangRoleRace, curRoleInfoConfig["f_RoleRace"]));
    this.txtArcAge.text = getLanguage(curRoleInfoConfig["f_RoleAge"]);
    this.txtArcBorn.text = getLanguage(curRoleInfoConfig["f_RoleBirthday"]);
    this.txtArcHeight.text = getLanguage(curRoleInfoConfig["f_RoleHeight"]);
    this.txtIntro.text = getLanguage(curRoleInfoConfig["f_RoleResume"]);

    --cv名根据 语言项 区分
    local _cvName = ""
    local _heroCV = G.dataTable["t_hero"][tostring(this.currentHeroData.partnerModelId)]["f_HeroCV"]
    if _heroCV then
        _cvName = getLanguage(_heroCV .. AudioManager.CurrentLanguageSuffix)
    end
    this.Txt_CvName.text = _cvName

    -- local pos = txtIntro.transform:InverseTransformPoint(Vector3.zero);
    --pos= rectContent.transform:TransformPoint(pos);

    --local nowHeight = pos.y+ txtIntro.preferredHeight+60;

    local lockLevels = decodeJsonStrToTabel(curRoleInfoConfig["f_RoleArchivesUnlock"]);

    for k, v in pairs(lockLevels) do
        local item = nil;
        if k <= #archivesTable then
            item = archivesTable[k];
        else
            item = UIPackage.CreateObject("CharactorUI", "UICharactorInfoArchivesItem")
            this.rectContent:AddChild(item)
            table.insert(archivesTable, item);
        end
        archivesTable[k].visible = true
        local data = {};
        data["title"] = getLanguage(string.format(Config.LangSpArchives, k));

        if lockLevels[k] <= this.currentHeroData.favorLv then
            data["content"] = getLanguage(curRoleInfoConfig["f_RoleArchives" .. tostring(k)]);
            data["unLock"] = true;
        else
            data["content"] = string.format(getLanguage("Sys_SpArchives5"),lockLevels[k]);
            data["unLock"] = false;
        end
        local ctrlItem = CtrlManager.GetCtrl(PanelNames.UICharactorInfoArchivesItem);
        if ctrlItem ~= nil and item ~= nil then
            item.visible = true
            ctrlItem.initData(item, data, LuaBehaviour);
        end
    end
    for i = #lockLevels + 1, #archivesTable do
        archivesTable[i].visible = false
    end
end

function UICharactorInfoArchives.onClickBack()
    this.objModel:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
    archivesTable = {}
    DestoryUI(PanelNames.UICharactorInfoArchives);
end
 
function UICharactorInfoArchives.renderListItemVoice(index, obj)
    local _currentIndex = index + 1
    local _interactionInfo = this.audioList[_currentIndex]
    local _title = getLanguage(AudioManager.InteractionTagTable[_interactionInfo.index].Name)
    obj:GetChild("title").text = _title
    local _selected = this.selectedVoiceIndex == _currentIndex
    if _selected then
        this.setSelectedVoice(obj)
    end
    local lockController = obj:GetController("lock");
    local lockCondition= obj:GetChild("title2")
    --解锁条件
    if string.IsNilOrEmpty(_interactionInfo.f_UnlockCondition) == false then
        --1：稀有度
        if _interactionInfo.f_UnlockCondition[1] == 1 then
            local _favorLv = this.currentHeroData.favorLv
            if _favorLv < _interactionInfo.f_UnlockCondition[2] then
                lockController:SetSelectedIndex(1);
                lockCondition.text = string.format(getLanguage("Sys_SpVoice"),_interactionInfo.f_UnlockCondition[2])
                if obj then
                    obj.selected = false
                end
                return
            end
        end
    end
    lockController:SetSelectedIndex(0);
    obj.selected = _selected
end
function this.setSelectedVoice(obj)
    local _interactionInfo = this.audioList[this.selectedVoiceIndex]
    --解锁条件
    if string.IsNilOrEmpty(_interactionInfo.f_UnlockCondition) == false then
        --1：稀有度
        if _interactionInfo.f_UnlockCondition[1] == 1 then
            local _favorLv = this.currentHeroData.favorLv
            if _favorLv < _interactionInfo.f_UnlockCondition[2] then
                UISysTips.AddMsg(getLanguage(_interactionInfo.f_UnlockDes))
                if obj then
                    obj.selected = false
                end
                return
            end
        end
    end
    this.checkStopVoice()
    local _interactionInfo = this.audioList[this.selectedVoiceIndex]
    local _interactionTag = AudioManager.InteractionTagTable[_interactionInfo.index].Tag

    local _partnerModelId = this.currentHeroData.partnerModelId
    local _skinId = 0
    local _introStr = ""
    local _controllerIndex = 0
    if not string.IsNilOrEmpty(_interactionInfo.f_LineText) then
        _introStr = getLanguage(_interactionInfo.f_LineText)
        if not string.IsNilOrEmpty(_introStr) then
            _controllerIndex = 1
        end
    end
    this.ShowLineTextController:SetSelectedIndex(_controllerIndex)
    this.Txt_IntroVoice.text = _introStr
    AudioManager.PlayInteractionVoice(_partnerModelId, _skinId, _interactionTag)
end

function this.onClickItemVoice(context)
    local _obj = context.data
    local _index = this.List_Voice:GetChildIndex(_obj)
    this.selectedVoiceIndex = _index + 1
    this.setSelectedVoice()
end
function this.onClickVoicePanel()
    this.cur_select_tab_index = 1
    this.tab_controller:SetSelectedIndex(this.cur_select_tab_index)

    this.audioList = {}
    local _skinId = 0
    local _partnerModelId = this.currentHeroData.partnerModelId
    for index, value in ipairs(AudioManager.InteractionTagTable) do
        local _interactionId = _partnerModelId .. _skinId .. value.Tag
        local _interactionInfo = G.dataTable["t_interaction"][tostring(_interactionId)]
        if _interactionInfo and _interactionInfo.f_Order and _interactionInfo.f_Order > 0 then
            local _audioIndex = _interactionInfo.f_Order
            _interactionInfo.index = index
            this.audioList[_audioIndex] = _interactionInfo
        end
    end
    this.List_Voice.numItems = #this.audioList
end
function this.onClickInfoPanel()
    this.cur_select_tab_index = 0
    this.tab_controller:SetSelectedIndex(this.cur_select_tab_index)
    this.checkStopVoice()
end
function this.checkStopVoice()
    AudioManager.TryStopInteractionVoice()
end

function this.onClickLeftPage()
    if this.selectedVoiceIndex > 1 then
        this.selectedVoiceIndex = this.selectedVoiceIndex - 1
        this.onClickVoicePanel()
        local _scrollIndex = this.selectedVoiceIndex > 3 and this.selectedVoiceIndex - 3 or 0
        this.List_Voice:ScrollToView(_scrollIndex)
    else
        local _count = #this.audioList
        this.selectedVoiceIndex = _count
        this.onClickVoicePanel()
        local _scrollIndex = _count - 1
        this.List_Voice:ScrollToView(_scrollIndex)
    end
end
function this.onClickRightPage()
    local _count = #this.audioList
    if this.selectedVoiceIndex < _count then
        this.selectedVoiceIndex = this.selectedVoiceIndex + 1
        this.onClickVoicePanel()
        local _scrollIndex = this.selectedVoiceIndex < _count and this.selectedVoiceIndex or _count - 1
        this.List_Voice:ScrollToView(_scrollIndex)
    else
        this.selectedVoiceIndex = 1
        this.onClickVoicePanel()
        local _scrollIndex =  0
        this.List_Voice:ScrollToView(_scrollIndex)
    end
end




--------------------------------------------
--- 英雄评论相关逻辑
--------------------------------------------
--切换评论面签回调
function UICharactorInfoArchives.onClickCommentPanel()
    this.checkStopVoice()
    this.cur_select_tab_index = 2
    this.tab_controller:SetSelectedIndex(this.cur_select_tab_index)
    -- print("切换评论面签") 
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroComment ) then
        this.comment_input_controller:SetSelectedIndex(1)
        local  singleConfig = G.dataTable["t_functionswitch"][tostring(Config.FuncOpenType.HeroComment)]
        local config = G.dataTable["t_stage"][tostring(singleConfig.f_UnlockStage)];
        if config ~= nil then
            local str = config.f_ChapterId .. "-" .. config.f_StageNum
            this.comment_input_tips1.text = string.format(getLanguage("FunctionTipsStage"), str) 
        else
            printError("t_stage 缺少解锁关卡 ", singleConfig.f_UnlockStage)
        end 
    elseif this.cur_hero_is_unown then
        this.comment_input_controller:SetSelectedIndex(2)
        this.comment_input_tips2.text = string.format(getLanguage("Achieve_HeroComment_NoHero"), this.currentHeroData.name) --"获得英雄后即可经行评论互动"
    else
         this.comment_input_controller:SetSelectedIndex(0)
    end

    -- this.list.numItems = #this.comments_data_list
    -- partnerHandler.sendGetHeroCommentsMessage( this.currentHeroData.partnerModelId ) 
    partnerHandler.HttpGetHeroCommentData( this.currentHeroData.partnerModelId )
end
 
-- 点击喜欢英雄
function UICharactorInfoArchives.onClickLikeHero()
    -- print("点击喜欢英雄") 
    if this.like_sp.grayed then
        this.like_sp.grayed = false
        this.like_hero_count = this.like_hero_count + 1
        if this.like_hero_count > 9999 then
            this.like_num.text = "9999+"
        else
            this.like_num.text = this.like_hero_count
        end
        local like_key = logicMgr.HeroManager.GetRoleId()..this.currentHeroData.partnerModelId
        local like_data_tb = {}
        like_data_tb.is_self_like = 1
        like_data_tb.like_count = this.like_hero_count
        local like_data_str = getJsonStr(like_data_tb);  
        Util.SetPlayerPrefs(like_key, like_data_str)
        partnerHandler.sendLikeHeroMessage( this.currentHeroData.partnerModelId ) 
    end
end
-- 发送评论
function UICharactorInfoArchives.onClickSendComment()

    local player_name = logicMgr.HeroManager.GetRoleName()
    local default_name = getLanguage("DefaultName")
    if player_name == default_name then
        UISysTips.AddMsg( getLanguage("Achieve_HeroComment_Msg_ChangeName") )
        showUI(PanelNames.UIPlayerChangeName)
        return
    end
    if this.cur_hero_is_unown then
        UISysTips.AddMsg(string.format(getLanguage("Achieve_HeroComment_NoHero"), this.currentHeroData.name) )
        return
    end

    local content = this.commend_input_content.text 
    content = string.gsub(content,"\r", "")
    content = string.gsub(content,"\n", "") 
    if content == "" then
        UISysTips.AddMsg(getLanguage("Sys_MsgInputEmpty"))
        return
    end 
    local limitCount = dataTable.getDataTableByStringId("t_global",281,"f_int_value")
    content = string.limitstr(content,limitCount);
    local source_content = content
    --blockword
    content = BlockWordFilter(content)
    --local blockword = dataTable.getDataTable("t_blockword")
    --for k, v in pairs(blockword) do
    --    content = string.gsub(content, v.f_Value, "**")
    --end
    if source_content ~= content then
        UISysTips.AddMsg(getLanguage("Achieve_HeroComment_Msg_BlockWord"))
        this.commend_input_content.text = content
        return
    end   
    partnerHandler.sendHeroCommentMessage( this.currentHeroData.partnerModelId, content) 
end
-- 更新评论列表数据
function UICharactorInfoArchives.renderListItemComment(index, obj) 
    local name_txt = obj:GetChild("name")
    local time_txt = obj:GetChild("time")
    local content_txt = obj:GetChild("text")
    local like_num_txt = obj:GetChild("num")
    local like_btn = obj:GetChild("btnFabulous")   
    local like_controller = like_btn:GetController("state") 
    local buzz_controller = obj:GetController("type")  
   
    local item_data = this.comments_data_list[index+1]
    local name = item_data and item_data.name  or "-"
    local time = item_data and item_data.time or os.time()
    local like_count = item_data and item_data.like_count or 0
    local is_self_like = item_data and item_data.is_self_like or 0
    local comment_str = item_data and item_data.comment_str  or ""
    local buzz_state = item_data and item_data.buzz_state or 0
    local comment_id = item_data and item_data.comment_id or -1

    local like_key = logicMgr.HeroManager.GetRoleId()..this.currentHeroData.partnerModelId..comment_id 
    local like_data_str = Util.GetPlayerPrefs(like_key) 
    if like_data_str ~= nil and like_data_str ~= "null" then
        local like_item_data = decodeJsonStrToTabel(like_data_str)
        if like_item_data.is_self_like and like_item_data.is_self_like == 1 then
            is_self_like = like_item_data.is_self_like
            this.comments_data_list[index+1].is_self_like = like_item_data.is_self_like
        end
        if like_item_data.like_count and like_item_data.like_count > like_count then
            like_count = like_item_data.like_count
            this.comments_data_list[index+1].like_count = like_item_data.like_count
        end
    end 
 
    buzz_controller:SetSelectedIndex(buzz_state)
    if this.cur_hero_is_unown then
        like_controller:SetSelectedIndex(0)
    else 
        if is_self_like == 1 then
            like_controller:SetSelectedIndex(2)
        else
            like_controller:SetSelectedIndex(1)
        end 
    end
    name_txt.text = name
    time_txt.text = os.date("%Y.%m.%d", time) 
    if like_count > 9999 then
        like_num_txt.text = "9999+"
    else
        like_num_txt.text = like_count
    end 
    content_txt.text = comment_str
    like_btn.onClick:Clear()
    like_btn.onClick:Add(function()  
        local item = this.comments_data_list[index+1]
        if  this.cur_hero_is_unown then  
            UISysTips.AddMsg(getLanguage("Achieve_HeroComment_Msg_NoHero"))
            return 
        elseif item and item.is_self_like ~= 1 then 
            like_controller:SetSelectedIndex(2) 
            local local_like_count = 0
            if this.comments_data_list and this.comments_data_list[index+1] then
                this.comments_data_list[index+1].like_count = this.comments_data_list[index+1].like_count + 1
                this.comments_data_list[index+1].is_self_like = true
                local_like_count = this.comments_data_list[index+1].like_count
            else
                local_like_count = local_like_count + 1 
            end
              
            local like_data_tb = {}
            like_data_tb.is_self_like = 1
            like_data_tb.like_count = local_like_count
            local like_key = logicMgr.HeroManager.GetRoleId()..this.currentHeroData.partnerModelId..item.comment_id
            local like_data_str = getJsonStr(like_data_tb) 
            Util.SetPlayerPrefs(like_key, like_data_str) 
            partnerHandler.sendGiveLikeCommentMessage( this.currentHeroData.partnerModelId, item.comment_id )
            -- this.list.numItems = #this.comments_data_list
            this.UpdateCommentsData()
        end
    end)
end

-- 拉取英雄评论
function UICharactorInfoArchives.ResGetHeroCommentsMessage( msg )
    this.comments_data_list = {}
    local hero_id = msg.heroModelId or 0 
    local key = logicMgr.HeroManager.GetRoleId().."_"..hero_id.."_hero_comment"
    this.like_hero_count = msg.likeCount or 0 
    this.is_self_like = msg.isSelfLiked or 0

    local like_key = logicMgr.HeroManager.GetRoleId()..this.currentHeroData.partnerModelId
    local like_data_str = Util.GetPlayerPrefs(like_key)
    if like_data_str ~= nil and like_data_str ~= "null" then
        local like_item_data = decodeJsonStrToTabel(like_data_str)
        if like_item_data.is_self_like and like_item_data.is_self_like == 1 then
            this.is_self_like = like_item_data.is_self_like
        end
        if like_item_data.like_count and like_item_data.like_count > this.like_hero_count then
            this.like_hero_count = like_item_data.like_count
        end
    end 

    this.like_num.text = this.like_hero_count
    if this.is_self_like == 0 then
        this.like_sp.grayed = true
    else
        this.like_sp.grayed = false
    end

    local comment_list ={}
    
    local oss_comment_list = partnerHandler.GetHeroCommentDataByHeroId( hero_id )
    for _, v in pairs(oss_comment_list) do
        comment_id = tostring(v.cid)
        local comment_data = {}  
        comment_data.name = v.name
        comment_data.like_count = 0
        comment_data.comment_str = v.content
        comment_data.buzz_state = 0
        comment_data.is_self_like = 0
        comment_data.time =  math.floor(tonumber(tostring(v.create_time))/1000) 
        comment_data.comment_id  = comment_id
        comment_data.comment_user_id = v.player_id 
        comment_list[comment_id] = comment_data
    end

    if msg.commentList then
        for k, v in pairs(msg.commentList) do
            if v then
                local praise_count = v.praiseCount or 0
                local is_self_like = v.isSelfLike or 0 --玩家自己是否点赞 0-未点赞 1-点赞
                local comment_id = tostring(v.commentId) 
                if comment_list[comment_id] ~= nil then
                    comment_list[comment_id].like_count = praise_count
                    comment_list[comment_id].is_self_like = is_self_like
                end 
            end
        end
    end

    local local_comments_str = Util.GetPlayerPrefs(key)
    -- print("---------------->key, local_comments_str:", key, local_comments_str)
    local local_comments = nil
    if local_comments_str and local_comments_str ~= "" then
        local_comments = decodeJsonStrToTabel(local_comments_str)
    end
    if local_comments then
        for k, v in pairs(local_comments) do
            local comment_id = tostring(v.comment_id)
            if comment_list[comment_id] == nil then
                comment_list[comment_id] = v
            end
        end
    end 
    local comment_count = 0
    for k, v in pairs(comment_list) do
        comment_count = comment_count + 1
        table.insert(this.comments_data_list, v)
    end  
    this.comment_num.text = getLanguage("Achieve_HeroComment_Count").."：" ..comment_count
    this.UpdateCommentsData() 
 
end

-- 更新评论列表数据
function UICharactorInfoArchives.UpdateCommentsData()
    if this.comments_data_list then
        -- table.sort(this.comments_data_list, function(a, b)
        --     return a.like_count > b.like_count
        -- end)
        if this.hot_comment_show_count == nil then
            this.hot_comment_show_count = dataTable.getDataTableByStringId("t_global",285,"f_int_value") or 2
        end  
        if this.hot_comment_min_like_count == nil then
            this.hot_comment_min_like_count = dataTable.getDataTableByStringId("t_global",286,"f_int_value") or 10
        end  

        for i = 1, this.hot_comment_show_count do
            if this.comments_data_list[i] and this.comments_data_list[i].like_count >= this.hot_comment_min_like_count then
                this.comments_data_list[i].buzz_state = 1
            end
        end

        table.sort(this.comments_data_list, function(a, b)
            if a.buzz_state == 1 and b.buzz_state ==1 then 
                if a.like_count == b.like_count then
                    return a.time > b.time
                else
                    return a.like_count > b.like_count
                end 
            elseif a.buzz_state == 1 and b.buzz_state == 0 then
                return true
            elseif a.buzz_state == 0 and b.buzz_state == 1 then
                return false
            else 
                return a.time > b.time 
            end
        end)
        this.list.numItems = #this.comments_data_list
    end
end

-- 喜好英雄请求返回
function UICharactorInfoArchives.ResLikeHeroMessage( msg ) 
end
 
-- 发送评论返回
function UICharactorInfoArchives.ResSendCommentMessage( msg ) 
    if msg.commentId then 
        this.commend_input_content.text = ""
 
        local heroid = msg.heroModelId or 0
        local key = logicMgr.HeroManager.GetRoleId().."_"..heroid.."_hero_comment"
        local comments = nil
        local comments_str = Util.GetPlayerPrefs(key)
        if comments_str and comments ~= "" then
            comments = decodeJsonStrToTabel(coments_str)
        end
        if comments == nil then
            comments = {}
        end
        if type(comments) ~= "table" then comments = {} end

        local player_name = msg.playerName
        
        local create_time = math.floor(tonumber(tostring(msg.time))/1000)
        local player_id = msg.playerId 
        local comment_str = msg.comment
        local comment_id = msg.commentId

        local comment_data = {} 
        comment_data.name = tostring(player_name)
        comment_data.like_count = 0
        comment_data.comment_str = tostring(comment_str)
        comment_data.buzz_state = 0
        comment_data.is_self_like = 0
        comment_data.time = create_time 
        comment_data.comment_id  = tostring(comment_id)
        comment_data.comment_user_id = tonumber(tostring(player_id))
        comments[comment_data.time] = comment_data
        
        local local_comments_list ={}
        for k, v in pairs(comments) do
            table.insert(local_comments_list, v)
        end
        table.sort(local_comments_list, function(a, b) 
            return a.time > b.time
        end)
        local local_limit_count = dataTable.getDataTableByStringId("t_global",282,"f_int_value")
        local count = 0 
        local save_comments_list = {}
        for k, v in ipairs(local_comments_list) do
            count = count+1
            if count <= local_limit_count then
                save_comments_list[v.time] = v 
            end
        end

        local save_comments_list_str = getJsonStr(save_comments_list)
        -- print("------------------------->key, save_comments_list_str:", key, save_comments_list_str)
        Util.SetPlayerPrefs(key, save_comments_list_str)
 
        table.insert(this.comments_data_list, comment_data)
        this.comment_num.text = getLanguage("Achieve_HeroComment_Count").."：" .. #this.comments_data_list
        this.UpdateCommentsData()
 
        if isOpenUI(PanelNames.UICharactorInfoHero) then
            local ui_charactor_info_hero = CtrlManager.GetCtrl(PanelNames.UICharactorInfoHero)
            if ui_charactor_info_hero ~= nil then
                ui_charactor_info_hero.AddCommentNum()
            end
        end

        if isOpenUI(PanelNames.UICharactorPreview) then
            local ui_charactor_preview = CtrlManager.GetCtrl(PanelNames.UICharactorPreview)
            if ui_charactor_preview ~= nil then
                ui_charactor_preview.AddCommentNum()
            end
        end

    end
end
-- 点赞请求响应
function UICharactorInfoArchives.ResGiveLikeCommentMessage(msg) 
end 
--------------------------------------------
--- end
--------------------------------------------



return UICharactorInfoArchives;
